package com.sosee.cgfw.friends;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sosee.cgfw.R;
import com.sosee.cgfw.activity.TicketDetialActivity;
import com.sosee.cgfw.entity.Data;
import com.sosee.cgfw.entity.PiaoJia;
import com.sosee.cgfw.entity.PiaoJiaData;
import com.sosee.cgfw.entity.PiaoJiaJson;
import com.sosee.cgfw.entity.ad.DataJson;
import com.sosee.cgfw.utils.Constans;
import com.sosee.cgfw.utils.LogUtils;
import com.sosee.cgfw.utils.Utils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Thinkpad on 2016/2/22.
 */
public class MyTicketActivity1 extends Activity implements View.OnClickListener {
    private RelativeLayout rl;
    List<Integer> plist=new ArrayList<Integer>();
    private int margin;
    private int total=5;
    private int size=4;
    private int height;
    private Map<Integer,View> map=new HashMap<Integer, View>();
    private List<Integer> posList=new ArrayList<Integer>();//用于记录view 的初始位置  方便计算 偏移量
    private boolean isZhankai=false;//判断 是否已经有 展开项 view
    private HttpUtils httpUtils=new HttpUtils();

    private List<Boolean> zlist=new ArrayList<Boolean>();//记录 各个view的展开状态
    private TextView tv_date;//日期选择
    String time="2015-10-30";
    private List<View> vlist=new ArrayList<View>();
    private String fiid;
    private String show;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_myticket1);
        Intent intent = getIntent();
        fiid = intent.getStringExtra("frId");

        RelativeLayout ig_fanhui_s=(RelativeLayout)findViewById(R.id.ig_fanhui_s);
        ig_fanhui_s.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        initUI();
        initData_web();
    }



    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    public void initUI(){

        tv_date= (TextView) findViewById(R.id.tv_date_se_s);
        Collections.sort(Utils.list_date);
        tv_date.setText(Utils.list_date.get(Utils.position));
    }


    //日期回退点击事件
    public void press(View view){


        if(Utils.position<1){
            Utils.position=0;
        }else{
            Utils.position=Utils.position-1;
        }
        time=Utils.list_date.get(Utils.position);
        tv_date.setText(time);
        if(rl!=null){
            rl.removeAllViews();
        }
        test(tlist);
    }
    //日期向后点击事件
    public void nextss(View view){
        if(Utils.position!=Utils.list_date.size()-1){
            Utils.position=Utils.position+1;
        }
        time=Utils.list_date.get(Utils.position);
        tv_date.setText(time);
        if(rl!=null){
            rl.removeAllViews();
        }
        test(tlist);


    }
    //变更日期 并转换为string
    public String dateChangData(String date,int i){

        String str=tv_date.getText().toString();
        SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
        Date d=null;
        try {
            d =sdf.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Calendar calendar = Calendar.getInstance();

        calendar.setTime(d);
        calendar.add(Calendar.DAY_OF_MONTH,i);
        SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
        String t = s.format(calendar.getTime());
        tv_date.setText(t);
        time=t;
        return t;
    }

    public void init(){
        margin=getWindowManager().getDefaultDisplay().getHeight()/size;
        height=(int)(getWindowManager().getDefaultDisplay().getHeight()/1.3f);
        LogUtils.log_E("height" + height);
    }

    public void initView(){
        vlist.clear();
        rl= (RelativeLayout) findViewById(R.id.ll_s);
        for (int i=0;i<total;i++){
            View v1=View.inflate(this,R.layout.item_childviews,null);
            RelativeLayout.LayoutParams params1=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,height);
            params1.topMargin=margin*i;
            v1.setLayoutParams(params1);
            v1.setId(i);
            v1.setOnClickListener(this);

            setViewData(v1,i);

            vlist.add(v1);
            rl.addView(v1);
            plist.add(i);
            posList.add(params1.topMargin);
            LogUtils.log_E("初始位置：" + params1.topMargin);
            zlist.add(false);
            map.put(i, v1);
        }


    }
    //给 每个view 设置数据
    public void setViewData(View v, final int position){
        TextView tv_start_time= (TextView) v.findViewById(R.id.tv_start_time_s);//开场时间
        TextView tv_title= (TextView) v.findViewById(R.id.tv_title_s);
        TextView tv_company= (TextView) v.findViewById(R.id.tv_company_s);
        TextView tv_company_e= (TextView) v.findViewById(R.id.tv_company_e_s);
        TextView tv_date= (TextView) v.findViewById(R.id.tv_date_s);
        TextView tv_time= (TextView) v.findViewById(R.id.tv_time_s);
        TextView tv_address= (TextView) v.findViewById(R.id.tv_address_s);
        TextView tv_address_e= (TextView) v.findViewById(R.id.tv_address_e_s);


        final Data data=temlist.get(position);
        tv_title.setText(data.getTitle());
        tv_company.setText(data.getUndertake());
        tv_company_e.setText(data.getUndertake_e());
        tv_date.setText(data.getStart_date());
        tv_time.setText(data.getEnter_time());
        tv_address.setText(data.getAddressA());
        tv_address_e.setText(data.getAddressA_e());
        tv_start_time.setText(data.getStart_time());
        final String showID=data.getID();
        show = data.getID();
//        Utils.showToast("show===" + show);
        ImageView ig_erweinma= (ImageView) v.findViewById(R.id.ig_erwei_s);
        LogUtils.log_E("二维码 宽高："+ig_erweinma.getWidth()+"height"+ig_erweinma.getHeight());
        ig_erweinma.setImageBitmap(Utils.createQRImage(erList.get(position), 800, 800));

        ImageView ig_zhuanzeng= (ImageView) v.findViewById(R.id.ig_zhuanzeng_s);
        ig_zhuanzeng.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                showPopup(v);

            }
        });

        ImageView ig_gengduo= (ImageView) v.findViewById(R.id.ig_gengduo_s);
        ig_gengduo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Utils.data=data;
                Intent intent=new Intent(MyTicketActivity1.this,TicketDetialActivity.class);
                startActivity(intent);
                finish();
            }
        });


    }


        //显示 弹框
        PopupWindow popupWindow=null;
        public void showPopup(View view) {
            popupWindow = new PopupWindow(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            View v = View.inflate(this, R.layout.pop_zhuanzeng_friends, null);

            popupWindow.setContentView(v);
            popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);

            v.findViewById(R.id.tv_cancle).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    closePopWindow();
                }
            });
            v.findViewById(R.id.tv_confim).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    donation();
                    closePopWindow();
                }
            });
        }
    //关闭 pop
    public void closePopWindow(){
        if (popupWindow!=null){
            popupWindow.dismiss();
        }
    }

    //转赠给好友 userID好友id
    public void donation(){
        httpUtils.send(HttpRequest.HttpMethod.GET, Constans.DONATIONFRIEND_URL+Constans.userID+"&showID=" + show + "&touserID=" + fiid, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                try {
                    org.json.JSONObject jsonObject=new org.json.JSONObject(responseInfo.result);
                    String status=jsonObject.getString("status");
                    if("success".equals(status)){
                        Utils.showToast("转赠成功");
                    }else{
                        String erro=jsonObject.getString("error");
                        if(erro.equals("邀请码已过期")){
                            Utils.showToast("您的邀请函已过期，转赠失败");
                        }
                        LogUtils.log_E("失败原因"+erro);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Utils.showToast("网络异常，转赠失败");
            }
        });
    }

//

//    @Override    //处理返回键
//    public void back(View view){
//        startActivity(new Intent(this,MyTicketActivity.class));
//        finish();
//
//    }
//    public void onBackPressed() {
//        startActivity(new Intent(this,MyTicketActivity.class));
//        finish();
//    }


    public void initData(){
//
        for (int i=1;i<posList.size();i++){
            int a=posList.get(i)+height;

            ylist.add(a);
            LogUtils.log_E("默认位置："+a);
            LogUtils.log_E("ylist默认："+ylist.get(i-1));
        }
    }


    View view;
    @Override
    public void onClick(View v) {

        int id=v.getId();

            List<Integer> temlist=new ArrayList<Integer>();
            temlist.addAll(plist);
            animation_zhankai(id, v, temlist);
        animation_zhankai_id(v.getId());
    }



    //展开指定id 的view视图
    public void animation_zhankai_id(int zID){
        {
            final View mView=map.get(plist.get(zID));
            final int log = 0-(int)mView.getY();
            TranslateAnimation tr=new TranslateAnimation(mView.getX(),mView.getX(),0,log);
            tr.setDuration(1000);
            tr.setInterpolator(new AccelerateDecelerateInterpolator());
            tr.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                }
                @Override
                public void onAnimationEnd(Animation animation) {
                    mView.clearAnimation();
                    int y=0;
                    RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,height);
                    params.topMargin=y;
                    mView.setLayoutParams(params);
                }
                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
            mView.startAnimation(tr);}



    }

    //刷新列表
    private List<Integer> ylist=new ArrayList<Integer>();
    public void animation_zhankai(int id,View v,List<Integer> plist){
        plist.remove((Integer)id);
        for (int i=0;i<plist.size();i++){
            final View mView=map.get(plist.get(i));
            if(plist.get(i)!=id){

//                final int log=height-margin;
                final int pos=ylist.get(i);
                final int
                log=ylist.get(i)-(int)mView.getY()-margin;
                TranslateAnimation tr=new TranslateAnimation(mView.getX(),mView.getX(),0,log);
                tr.setDuration(1000);
                tr.setInterpolator(new AccelerateDecelerateInterpolator());
                tr.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {
                    }
                    @Override
                    public void onAnimationEnd(Animation animation) {
                        mView.clearAnimation();
                        int y=pos-margin;
                        RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,height);
                        params.topMargin=y;
                        mView.setLayoutParams(params);
                    }
                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
                mView.startAnimation(tr);
            }else{
                int pianyi=(int)v.getY();
                int log=0-pianyi;
                TranslateAnimation tr=new TranslateAnimation(mView.getX(),0,0,log);
                LogUtils.log_E("xiangshang:"+mView.getY());
                tr.setDuration(1000);
                tr.setInterpolator(new AccelerateDecelerateInterpolator());
                tr.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        mView.clearAnimation();
                        int y = 0;
                        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, height);
                        params.topMargin = y;
                        mView.setLayoutParams(params);
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
                mView.startAnimation(tr);
            }

        }
    }




    public void animation_shouhui(int id){
        for (int i=0;i<plist.size();i++) {
            final View mView = map.get(plist.get(i));
            if (plist.get(i) != id) {
                final int mID=plist.get(i);
                final int log = 0-height+margin;
                TranslateAnimation tr = new TranslateAnimation(mView.getX(), mView.getX(), 0, log);
                tr.setDuration(1000);
                tr.setInterpolator(new AccelerateDecelerateInterpolator());
                tr.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        mView.clearAnimation();
                        int y = posList.get(mID);
                        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, height);
                        params.topMargin = y;
                        LogUtils.log_E("y=============" + y + ";;;;id=" + mView.getId());
                        mView.setLayoutParams(params);
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
                mView.startAnimation(tr);
            }
        }
    }


    //处理导航条点击事件
    public void click(View view){
        int id=view.getId();
        switch (id){
            //返回键
            case R.id.ig_fanhui:
                finish();
                break;
//            //邀请函
//            case R.id.ig_yaoqinghan:
//                startActivity(new Intent(this, InvitationActivity.class));
//                finish();
//                break;
//            //申请
//            case R.id.ig_shenqing:
//                startActivity(new Intent(this,ApplyActivity.class));
//                finish();
//                break;

        }
    }


    private List<Data> tlist=new ArrayList<Data>();
    private List<String> erList=new ArrayList<String>();
    public void initData_web(){

        httpUtils.configCurrentHttpCacheExpiry(1000 * 1);
        httpUtils.send(HttpRequest.HttpMethod.GET, Constans.PIAO_URL+Constans.userID, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                try {
                    org.json.JSONObject jsonObject=new org.json.JSONObject(responseInfo.result);
                    String status=jsonObject.getString("status");
                    if("success".equals(status)){
                        PiaoJiaJson pjson = JSONObject.parseObject(responseInfo.result, PiaoJiaJson.class);
                        List<PiaoJia> list = pjson.getResult();
                        if (list != null) {
                        } else {
                            Utils.showToast("解析json出错");
                        }
                        initUI(list);
                    }else{

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(HttpException e, String s) {
                Utils.showToast("网络异常"+s);
            }
        });
    }

    public void initUI(List<PiaoJia> list){
        Utils.piaoJiaList.clear();
        Utils.shenQingList.clear();
        for (int i=0;i<list.size();i++){
            PiaoJiaData pdata=list.get(i).getData();
            String status=pdata.getStatus();
            if(status!=null){

                LogUtils.log_E("status="+status+"===");
                if(status.equals("1")||status.equals("4")){
                    if(pdata.getShow()!=null&&pdata.getShow().size()>0){
                        String show=pdata.getShow().get(0);
                        Data data= JSONArray.parseArray(show,DataJson.class).get(0).getData();
                        tlist.add(data);
                        LogUtils.log_E("二维码信息：" + pdata.getInfo());
                        erList.add(pdata.getInfo());
                    }

                }else if(status.equals("2")||status.equals("3")){
                    Utils.piaoJiaList.add(pdata);
                }else if(status.equals("5")||status.equals("6")){
                    Utils.shenQingList.add(pdata);
                }


            }else{
            }

        }
        test(tlist);
    }
    private List<Data> temlist;
    public void test(List<Data> tlist){
        temlist =new ArrayList<Data>();
        for (int n=0;n<tlist.size();n++){
            if(tlist.get(n).getStart_date().equals(Utils.list_date.get(Utils.position))){
                temlist.add(tlist.get(n));
            }
        }
        total=temlist.size();
        LogUtils.log_E("测试 邀请函："+Utils.position+"个数："+total);
        if(total>0){
            init();
            initView();
            initData();
        }
    }



}

